package com.mobile_fault_detector.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mobile_fault_detector.common.Constants;
import com.mobile_fault_detector.dto.AIQueryRequest;
import com.mobile_fault_detector.dto.AIResponse;
import com.mobile_fault_detector.dto.KeywordQueryRequest;
import com.mobile_fault_detector.entity.KeywordEventMapping;
import com.mobile_fault_detector.entity.TrackingEvent;
import com.mobile_fault_detector.mapper.IKeywordEventMappingMapper;
import com.mobile_fault_detector.mapper.ITrackingEventMapper;
import com.mobile_fault_detector.service.IKeywordEventService;
import com.mobile_fault_detector.utils.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 关键词事件服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class KeywordEventServiceImpl implements IKeywordEventService {

    private final IKeywordEventMappingMapper IKeywordEventMappingMapper;
    private final ITrackingEventMapper ITrackingEventMapper;
    private final RestTemplate restTemplate;
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public Result getAnswer(String query) {
        log.info("根据用户问题获取AI回答");

        try {
            // 1. 调用AI接口获取关键词
            String keywords = getKeywordsFromAI(query);

            if (keywords == null || keywords.trim().isEmpty()) {
                return Result.fail("获取关键词失败");
            }

            // 2. 使用获取到的关键词调用getAnswerByKeyword方法查询埋点
            KeywordQueryRequest request = new KeywordQueryRequest();
            request.setAnswer(keywords);
            request.setQuery(query);
            return getAnswerByKeyword(request);
        } catch (Exception e) {
            log.error("根据用户问题获取AI回答失败，问题: {}, 异常信息: {}", query, e.getMessage(), e);
            return Result.fail("获取AI回答失败");
        }
    }

    /**
     * 调用AI接口获取关键词
     * @param query 用户问题
     * @return JSON格式的关键词列表
     */
    private String getKeywordsFromAI(String query) {
        log.info("调用AI接口获取关键词");

        try {
            // 构建请求参数
            Map<String, String> requestMap = new HashMap<>();
            requestMap.put("query", query);

            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("x-api-key", Constants.API_KEY);

            // 创建请求实体
            HttpEntity<Map<String, String>> requestEntity = new HttpEntity<>(requestMap, headers);

            // 发送POST请求并获取响应
            KeywordQueryRequest keywordQueryRequest = restTemplate.postForObject(Constants.KEYWORD_AI_API_URL, requestEntity, KeywordQueryRequest.class);
            log.info("收到AI关键词接口响应: {}", keywordQueryRequest.getAnswer());

            return  keywordQueryRequest.getAnswer();
        } catch (Exception e) {
            log.error("调用AI接口获取关键词失败，异常信息: {}", e.getMessage(), e);
            return null;
        }
    }

    /**
     * 根据关键词查询埋点
     * @param request 关键词的封装类
     * @return JSON格式的关键词列表
     */
    private Result getAnswerByKeyword(KeywordQueryRequest request) {
        log.info("根据关键词查询埋点事件并获取AI回答");
        
        // 1. 根据关键词查询埋点事件类型
        List<String> eventTypes = getEventTypesByKeyword(request.getAnswer());
        log.info("查询到的埋点事件类型: {}", eventTypes);
        
        if (eventTypes.isEmpty()) {
            // 如果没有找到对应的埋点事件类型，直接将用户问题发送给AI端
            return getAnswerFromAI(request.getAnswer(), new ArrayList<>());
        }
        
        // 2. 根据埋点事件类型查询埋点事件JSON信息
        List<String> eventJsonList = getEventJsonsByEventTypes(eventTypes);
        
        // 3. 将用户问题和埋点事件JSON信息发送给AI端获取回答
        return getAnswerFromAI(request.getQuery(), eventJsonList);
    }
    
    /**
     * 根据关键词查询埋点事件类型
     * @param keywordInput 关键词（可能是JSON格式的关键词列表或普通关键词）
     * @return 埋点事件类型列表
     */
    private List<String> getEventTypesByKeyword(String keywordInput) {
        List<String> eventTypes = new ArrayList<>();
        List<String> keywordList = new ArrayList<>();
        
        // 检查输入是否为JSON格式的关键词列表
        log.info("原始关键词输入: {}", keywordInput);
        
        if (keywordInput.startsWith("[") && keywordInput.endsWith("]")) {
            // 解析JSON格式的关键词列表
            String cleanedJson = keywordInput.replace("[", "").replace("]", "").replace("\"", "").replace("'", "");
            String[] keywords = cleanedJson.split(",");
            for (String k : keywords) {
                String trimmed = k.trim();
                if (!trimmed.isEmpty()) {
                    keywordList.add(trimmed);
                }
            }
        } else {
            log.info("使用空格分割普通关键词");
            // 按空格分割普通关键词
            String[] keywords = keywordInput.split("\\s+");
            for (String k : keywords) {
                String trimmed = k.trim();
                if (!trimmed.isEmpty()) {
                    keywordList.add(trimmed);
                }
            }
        }
        
        log.info("解析后的关键词列表: {}", keywordList);
        
        // 如果没有有效关键词，直接返回空列表
        if (keywordList.isEmpty()) {
            return eventTypes;
        }
        
        // 尝试两种查询方式
        List<KeywordEventMapping> mappings = new ArrayList<>();
        
        // 1. 首先尝试精确匹配（因为keywords是主键）
//        log.info("尝试精确匹配查询");
//        for (String k : keywordList) {
//            LambdaQueryWrapper<KeywordEventMapping> exactWrapper = new LambdaQueryWrapper<>();
//            exactWrapper.eq(KeywordEventMapping::getKeywords, k);
//            List<KeywordEventMapping> exactMappings = keywordEventMappingMapper.selectList(exactWrapper);
//            if (!exactMappings.isEmpty()) {
//                log.info("精确匹配到关键词: {}", k);
//                mappings.addAll(exactMappings);
//            }
//        }
        
        // 2. 如果精确匹配没有结果，尝试模糊查询
        if (mappings.isEmpty()) {
            log.info("尝试模糊查询");
            LambdaQueryWrapper<KeywordEventMapping> likeWrapper = new LambdaQueryWrapper<>();
            
            // 对每个关键词使用OR条件
            for (int i = 0; i < keywordList.size(); i++) {
                String k = keywordList.get(i);
                // 第一个条件使用like，后续条件使用or
                if (i == 0) {
                    likeWrapper.like(KeywordEventMapping::getKeywords, "%" + k + "%");
                } else {
                    likeWrapper.or().like(KeywordEventMapping::getKeywords, "%" + k + "%");
                }
            }
            
            mappings = IKeywordEventMappingMapper.selectList(likeWrapper);
            log.info("模糊查询结果数量: {}", mappings.size());
        }
        
        // 提取所有匹配记录中的埋点事件类型
        for (KeywordEventMapping mapping : mappings) {
            log.info("处理映射记录: keywords={}, eventTypes={}", mapping.getKeywords(), mapping.getEventTypes());
            
            // eventTypes字段现在是JSON格式，需要解析
            String eventTypesJson = mapping.getEventTypes();
            // 去掉JSON数组的方括号和引号
            String cleanedJson = eventTypesJson.replace("[", "").replace("]", "").replace("\"", "");
            
            String[] types = cleanedJson.split(",");
            for (String type : types) {
                eventTypes.add(type.trim());
            }
        }
        
        return eventTypes;
    }
    
    /**
     * 根据埋点事件类型查询埋点事件JSON信息
     * @param eventTypes 埋点事件类型列表
     * @return 埋点事件JSON信息列表
     */
    private List<String> getEventJsonsByEventTypes(List<String> eventTypes) {
        List<String> eventJsonList = new ArrayList<>();
        
        // 查询每个埋点事件类型对应的埋点事件JSON信息
        for (String eventType : eventTypes) {
            LambdaQueryWrapper<TrackingEvent> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TrackingEvent::getEventType, eventType.trim());
            List<TrackingEvent> events = ITrackingEventMapper.selectList(wrapper);
            
            // 提取埋点事件JSON信息
            for (TrackingEvent event : events) {
                eventJsonList.add(event.getEventDescription());
            }
        }
        
        return eventJsonList;
    }
    
    /**
     * 将用户问题和埋点事件JSON信息发送给AI端获取回答
     * @param query 用户问题
     * @param eventJsonList 埋点事件JSON信息列表
     * @return AI回答响应
     */
    private Result getAnswerFromAI(String query, List<String> eventJsonList) {
        // 构建请求对象
        AIQueryRequest aiQueryRequest = new AIQueryRequest();
        aiQueryRequest.setQuery(query);

        //将jsonArrayString转为字符串
        Gson gson=new Gson();
        String eventJsonString = gson.toJson(eventJsonList);
        aiQueryRequest.setEventJsonList(eventJsonString);

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("x-api-key", Constants.API_KEY);
        
        // 创建请求实体
        HttpEntity<AIQueryRequest> requestEntity = new HttpEntity<>(aiQueryRequest, headers);
        
        // 发送POST请求并获取响应
        log.info("发送请求到AI端，请求内容: {}", aiQueryRequest);
        AIResponse response = restTemplate.postForObject(Constants.AI_API_URL, requestEntity, AIResponse.class);
        log.info("收到AI端响应: {}", response);
        return Result.ok(response);
    }
    
}